package cn.doitedu.sql;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.triggers.Trigger;
import org.apache.flink.streaming.api.windowing.triggers.TriggerResult;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.HashSet;

public class _19_Advance_Trigger_Exercise {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        // a,10000
        // b,11000
        DataStreamSource<String> stream = env.socketTextStream("localhost", 8899);

        SingleOutputStreamOperator<Tuple2<String, Long>> mapped = stream.map(new MapFunction<String, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(String line) throws Exception {
                String[] split = line.split(",");
                return Tuple2.of(split[0], Long.parseLong(split[1]));
            }
        });

        SingleOutputStreamOperator<Tuple2<String, Long>> watermarked = mapped.assignTimestampsAndWatermarks(
                WatermarkStrategy.<Tuple2<String, Long>>forBoundedOutOfOrderness(Duration.ZERO)
                        .withTimestampAssigner(new SerializableTimestampAssigner<Tuple2<String, Long>>() {
                            @Override
                            public long extractTimestamp(Tuple2<String, Long> tp, long recordTimestamp) {
                                return tp.f1;
                            }
                        })

        );

        watermarked.keyBy(tp -> tp.f0)
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .trigger(new MyTrigger(1000))
                .process(new ProcessWindowFunction<Tuple2<String, Long>, Integer, String, TimeWindow>() {
                    @Override
                    public void process(String s, ProcessWindowFunction<Tuple2<String, Long>, Integer, String, TimeWindow>.Context context, Iterable<Tuple2<String, Long>> elements, Collector<Integer> out) throws Exception {
                        int cnt = 0;
                        for (Tuple2<String, Long> element : elements) {
                            cnt++;
                        }
                        out.collect(cnt);
                    }
                }).print();

        env.execute();
    }
}


class MyTrigger extends Trigger<Tuple2<String, Long>, TimeWindow> {
    HashSet<TimeWindow> timeWindows;
    long triggerInterval;

    public MyTrigger(long triggerInterval) {
        this.triggerInterval = triggerInterval;

        timeWindows = new HashSet<>();
    }


    /**
     * 当窗口进入了一条数据，会调用
     * 返回是否要触发计算
     */
    @Override
    public TriggerResult onElement(Tuple2<String, Long> element, long timestamp, TimeWindow window, TriggerContext ctx) throws Exception {

        // 先把数据按1s对齐
        long trunked = timestamp - timestamp % triggerInterval;

        if (!timeWindows.contains(window)) {
            // 如果本次进入的element是本窗口的第一条数据，则注册定时器：1秒后
            long timerTime = trunked + triggerInterval - 1;
            ctx.registerEventTimeTimer(timerTime);

            timeWindows.add(window);

            //System.out.printf("onElement, window_start: %d ,timestamp: %d , trunked: %d ,定时器时间: %d \n",window.getStart(),timestamp,trunked,timerTime);
        }

        return TriggerResult.CONTINUE;
    }


    /**
     * 当处理时间语义的定时器触发时，会调用本方法
     * 返回：是否要触发窗口计算
     */
    @Override
    public TriggerResult onProcessingTime(long time, TimeWindow window, TriggerContext ctx) throws Exception {
        return null;
    }


    /**
     * 当事件时间语义的定时器触发时，会调用本方法
     * 返回：是否要触发窗口计算
     */
    @Override
    public TriggerResult onEventTime(long time, TimeWindow window, TriggerContext ctx) throws Exception {

        long newTimer = time + 1000;
        ctx.registerEventTimeTimer(newTimer);

        //System.out.printf("onEventTime 被调用,注册了新的定时器： %d \n", newTimer);

        return TriggerResult.FIRE;
    }


    /**
     * 窗口结束了且触发完了，这个窗口没用了，会调用本方法，来做一些清理工作
     */
    @Override
    public void clear(TimeWindow window, TriggerContext ctx) throws Exception {

    }
}